<template>
  <el-upload
    ref="upload"
    v-model:file-list="imgUrl"
    accept=".png,.jpg,.jpeg,.bmp"
    list-type="picture-card"
    :http-request="uploadFile"
    :limit="1"
    :on-exceed="handleExceed"
    :before-upload="handleBeforeUpload"
  >
    <!-- :http-request="uploadFile" -->
    <el-icon><Plus /></el-icon>
    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <!-- <el-button type="primary" round size="small">重新上传</el-button> -->
          <el-button type="warning" round size="small" @click="deleteImg"
            >删除</el-button
          >
        </span>
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { UploadProps, UploadRawFile } from "element-plus";
import { computed, ref } from "vue";

let upload = ref();
type PropsType = {
  imgUrl: any[];
};
let props = withDefaults(defineProps<PropsType>(), {
  imgUrl: [] as any,
});
let emit = defineEmits(["update:imgUrl", "getFile"]);
let imgUrl = computed({
  get() {
    return props.imgUrl;
  },
  set(val) {
    emit("update:imgUrl", val);
  },
});

const handleBeforeUpload = (file: any) => {
  if (file.size > 2 * 1048 * 1048) {
    ElMessage.warning("上传图片不能大于2M");
    return false;
  }
  return true;
};
const uploadFile: any = (option) => {
  console.log(option, imgUrl.value);
  emit("getFile", option.file);
  // console.log("unmg", imgUrl.value);
};
const deleteImg = () => {
  upload.value!.clearFiles();
};
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  upload.value!.handleStart(file);
};
</script>

<style scoped lang="scss"></style>
